package com.lingkang.ngfile.config.security;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 用户登录失败时返回给前端的数据
 **/
@Component
public class AjaxAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException {
        String res;
        if (exception instanceof UsernameNotFoundException) {
            res = "1";
        } else if (exception instanceof BadCredentialsException) {
            res = "2";
        } else if (exception instanceof LockedException) {
            res = "3";
        } else if (exception instanceof DisabledException) {
            res = "4";
        } else if (exception instanceof AccountExpiredException) {
            res = "5";
        } else if (exception instanceof CredentialsExpiredException) {
            res = "6";
//        } else if(exception instanceof TokenInvalidException) {
//            ResultEnum.USER_LOGIN_FAILED .setMessage( "登陆信息已过期,请重新登陆";
        } else {
            res = "7";
        }
        httpServletResponse.getWriter().write(res);
    }
}
